<template>
  <div class="upload-container">
    <div class="header-row">
      <h2>智能文件上传</h2>
      <el-button
        v-if="chunks.length > 0"
        type="primary"
        @click="handleSubmit"
        class="submit-btn"
        :loading="loading"
      >
        提交
      </el-button>
    </div>
    <p v-if="fileName" class="file-name">当前文件: {{ fileName }}</p>
    <FileUpload
      ref="fileUploadRef"
      @upload-success="handleSuccess"
      @close-dialog="$emit('close-dialog')"
    />

    <div v-if="chunks.length > 0" class="chunk-list">
      <h3>文件分块预览</h3>
      <el-card v-for="chunk in chunks" :key="chunk.chunkId" class="chunk-item">
        <template #header>
          <div class="flex justify-between items-center">
            <span>分块 #{{ chunk.chunkId }}</span>
            <el-tag type="info">{{ chunk.keywords.length }} 关键词</el-tag>
            <el-tooltip
              effect="light"
              :content="chunk.keywords.join(', ')"
              placement="top"
              popper-class="keyword-tooltip"
            >
              <el-tag type="info" class="keyword-tag" size="small">
                {{ chunk.keywords.slice(0, 10).join(', ')
                }}{{ chunk.keywords.length > 10 ? '...' : '' }}
              </el-tag>
            </el-tooltip>
          </div>
        </template>
        <div class="chunk-content">
          {{ chunk.content }}
        </div>
      </el-card>
    </div>
  </div>
</template>

<style scoped>
.keyword-tag {
  margin: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.keyword-tag:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.upload-container {
  max-width: 800px;
  margin: 2rem auto;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.chunk-list {
  margin-top: 2rem;
}

.chunk-item {
  margin-bottom: 1rem;
}

.chunk-content {
  white-space: pre-wrap;
  max-height: 300px;
  overflow-y: auto;
  padding: 10px;
  background: #f8f8f8;
  border-radius: 4px;
}

.header-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
}

h2 {
  color: #2c3e50;
  margin: 0;
}

.submit-btn {
  margin-left: 1rem;
}

.file-name {
  color: #495057;
  margin-bottom: 1rem;
  text-align: center;
  font-size: 1.1rem;
}
</style>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import FileUpload from '@/components/FileUpload.vue'
import { preUpload, confirmUpload } from '@/api/fileApi'

const fileUploadRef = ref<InstanceType<typeof FileUpload>>()

const emit = defineEmits(['upload-success', 'close-dialog'])

type Chunk = {
  content: string
  chunkId: number
  keywords: string[]
}

const chunks = ref<Chunk[]>([])
const fileName = ref('')
const selectedTypeId = ref(0)
const selectedChunkType = ref(1)

const handleSuccess = (data: {
  chunks: Chunk[]
  filename: string
  typeId: number
  chunkType: number
}) => {
  chunks.value = data.chunks
  fileName.value = data.filename
  selectedTypeId.value = data.typeId
  selectedChunkType.value = data.chunkType
}

const reset = () => {
  fileUploadRef.value?.reset()
  chunks.value = []
  fileName.value = ''
}

defineExpose({
  reset,
})

const loading = ref(false)

const handleSubmit = async () => {
  loading.value = true
  try {
    const payload = {
      filename: fileName.value,
      chunkType:
        selectedChunkType.value === 0
          ? '不切分'
          : selectedChunkType.value === 1
            ? '固定长度切分'
            : '标题增强切分',
      typeName: fileName.value.split('.').pop(),
      typeId: selectedTypeId.value,
      chunks: chunks.value,
    }

    const res = await confirmUpload(payload)
    if (res.data.code === 200) {
      ElMessage.success(res.data.msg)
      // 触发父组件刷新列表和关闭弹窗
      emit('upload-success', { chunks: [], filename: '' })
      emit('close-dialog', true)
    } else {
      ElMessage.error(res.data.msg)
    }
  } catch (error: unknown) {
    console.error('提交失败:', error)
    if (error instanceof Error) {
      ElMessage.error('提交失败：' + error.message)
    } else {
      ElMessage.error('提交失败')
    }
  } finally {
    loading.value = false
  }
}
</script>
